//
//  CommentTeacherViewController.m
//  ZPIOSEducation
//
//  Created by 董伟1 on 17/1/16.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "CommentTeacherViewController.h"
#import "AutoSizeLabelView.h"

@interface CommentTeacherViewController () <UIScrollViewDelegate,UITextViewDelegate,AutoSizeLabelDelegate>
{
    AutoSizeLabelView  *autoSizeLabView;
    NSString  *totalScore;
    NSString  *levelScore;
    NSString  *attitudeScore;
    
    NSMutableArray  *labelDataArray;
    
}
@property (weak, nonatomic) IBOutlet UIScrollView *mainScrollView;

@property (weak, nonatomic) IBOutlet UIImageView *headerImv;
@property (weak, nonatomic) IBOutlet UILabel *nameLab;
@property (weak, nonatomic) IBOutlet UIView *labelView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *labelViewHeight;
@property (weak, nonatomic) IBOutlet UITextView *commentTextView;
@property (weak, nonatomic) IBOutlet UISwitch *hiddenNameSwitch;
@property (weak, nonatomic) IBOutlet UIButton *commitBtn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineHeight;

@property (weak, nonatomic) IBOutlet UILabel *placeholderLab;
@property (weak, nonatomic) IBOutlet UILabel *numLab;


@end

@implementation CommentTeacherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"评价";
    self.lineHeight.constant = 0.5;
    self.headerImv.contentMode = UIViewContentModeScaleAspectFill;
    self.headerImv.clipsToBounds = YES;
    self.headerImv.layer.cornerRadius = 30.;
    self.headerImv.layer.masksToBounds = YES;
    self.labelView.hidden = YES;
    self.numLab.hidden = YES;
    self.labelViewHeight.constant = 0.;
    
    autoSizeLabView = [[AutoSizeLabelView  alloc] initWithFrame:CGRectMake(5, 0, SCREENWIDTH - 10, 0)];
    autoSizeLabView.autoSizeLabDelegate = self;
    [self.labelView  addSubview:autoSizeLabView];
    
    self.commentTextView.layer.cornerRadius = 4.;
    self.commentTextView.layer.masksToBounds = YES;
    self.commentTextView.layer.borderColor = [UIColor  colorWithRed:238/255. green:238/255. blue:238/255. alpha:1.].CGColor;
    self.commentTextView.layer.borderWidth = 0.5;
    self.commentTextView.delegate = self;
    
    self.commitBtn.layer.cornerRadius = 4.;
    self.commitBtn.layer.masksToBounds = YES;
    [self.commitBtn  addTarget:self action:@selector(commitButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.headerImv.image = [UIImage  imageNamed:@"Placeholder200_200"];
    totalScore = @"0";
    levelScore = @"0";
    attitudeScore = @"0";
    
    labelDataArray = [[NSMutableArray  alloc] init];
    
    if (self.teacherId) {
        [self  requestTeacherInfo];
    }
    
}

#pragma mark - Button Actions
#pragma mark 总分数
- (IBAction)totalScoreButtonClick:(id)sender
{
    self.labelView.hidden = NO;
    self.labelViewHeight.constant = autoSizeLabView.frame.size.height + 110;
    
    [self.commitBtn  setBackgroundColor:RGBACOLOR(33, 164, 235, 1.)];
    self.commitBtn.userInteractionEnabled = YES;
    
    UIButton  *tempBtn = (UIButton  *)sender;
    UIView  *totalScoreView = (UIView  *)[self.mainScrollView  viewWithTag:100];
    NSInteger tag = tempBtn.tag;
    if ([totalScore  integerValue] == tag - 1000) {
        return;
    }
    
    for (UIView  *tempView in totalScoreView.subviews) {
        if (tempView.tag >= 1000 && [tempView  isKindOfClass:[UIButton  class]]) {
            UIButton  *scoreBtn = (UIButton  *)tempView;
            if (scoreBtn.tag > tag) {
                scoreBtn.selected = NO;
            }else {
                scoreBtn.selected = YES;
            }
        }
    }
    
    totalScore = [NSString  stringWithFormat:@"%ld",tag - 1000];
}

#pragma mark 教学水平
- (IBAction)levelScoreButtonClick:(id)sender
{
    UIButton  *tempBtn = (UIButton  *)sender;
    UIView  *levelScoreView = (UIView  *)[self.mainScrollView  viewWithTag:200];
    NSInteger tag = tempBtn.tag;
    if ([levelScore  integerValue] == tag - 2000) {
        return;
    }
    
    for (UIView  *tempView in levelScoreView.subviews) {
        if (tempView.tag >= 2000 && tempView.tag < 3000 && [tempView  isKindOfClass:[UIButton  class]]) {
            UIButton  *scoreBtn = (UIButton  *)tempView;
            if (scoreBtn.tag > tag) {
                scoreBtn.selected = NO;
            }else {
                scoreBtn.selected = YES;
            }
        }
    }
    
    levelScore = [NSString  stringWithFormat:@"%ld",tag - 2000];
}

#pragma mark 教学态度
- (IBAction)attitudeButtonClick:(id)sender
{
    UIButton  *tempBtn = (UIButton  *)sender;
    UIView  *attitudeScoreView = (UIView  *)[self.mainScrollView  viewWithTag:200];
    NSInteger tag = tempBtn.tag;
    if ([attitudeScore  integerValue] == tag - 3000) {
        return;
    }
    
    for (UIView  *tempView in attitudeScoreView.subviews) {
        if (tempView.tag >= 3000 && [tempView  isKindOfClass:[UIButton  class]]) {
            UIButton  *scoreBtn = (UIButton  *)tempView;
            if (scoreBtn.tag > tag) {
                scoreBtn.selected = NO;
            }else {
                scoreBtn.selected = YES;
            }
        }
    }
    
    levelScore = [NSString  stringWithFormat:@"%d",tag - 3000];
}

- (void)commitButtonClick:(id)sender
{
    NSMutableDictionary  *paramDic = [NSMutableDictionary  dictionaryWithObjectsAndKeys:
                                      [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"stuId"],@"studentId",
                                      totalScore,@"score",
                                      nil];
    if ([levelScore integerValue] > 0) {
        [paramDic  setObject:levelScore forKey:@"teachingLevelScore"];
    }
    if ([attitudeScore integerValue] > 0) {
        [paramDic  setObject:attitudeScore forKey:@"teachingAttitudeScore"];
    }
    if (self.scheduleId) {
        [paramDic  setObject:[NSString  stringWithFormat:@"%@",self.scheduleId] forKey:@"scheduleId"];
    }
    if (self.teacherId) {
        [paramDic  setObject:[NSString  stringWithFormat:@"%@",self.teacherId] forKey:@"teacherId"];
    }
    NSString  *isAnonymous = @"0";
    if (self.hiddenNameSwitch.on) {
        isAnonymous = @"1";
    }
    [paramDic  setObject:isAnonymous forKey:@"isAnonymous"];
    
    if (self.commentTextView.text.length > 0) {
        [paramDic  setObject:self.commentTextView.text forKey:@"remark"];
    }
    
    NSMutableArray  *remarkLabelArr = [[NSMutableArray  alloc] init];
    for (UIView  *tempView in autoSizeLabView.subviews) {
        if ([tempView  isKindOfClass:[SelectLabel  class]] && tempView.tag >= 2000) {
            SelectLabel  *label = (SelectLabel *)tempView;
            if (label.selected) {
                [remarkLabelArr  addObject:[[labelDataArray  objectAtIndex:label.tag - 2000] objectForKey:@"name"]];
            }
        }
    }
    if (remarkLabelArr.count > 0) {
        [paramDic  setObject:[NSString  stringWithFormat:@"%@",[remarkLabelArr  componentsJoinedByString:@","]] forKey:@"remarkLabel"];
    }
    [self  showHudithString:@"发送中..."];
    [[ZPNetworking  sharedZPNetworking] POST:APIHome@"home/saveEvaluation.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                [ZPPromptView  showMessage:@"评价提交成功"];
                [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshCourseList" object:nil];
                [self.navigationController  popViewControllerAnimated:YES];
            }
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

#pragma mark - 网络相关
#pragma mark 获取老师信息
- (void)requestTeacherInfo
{
    [self  showHudithString:@"加载中..."];
    NSMutableDictionary  *paramDic = [NSMutableDictionary  dictionaryWithObjectsAndKeys:[NSString  stringWithFormat:@"%@",self.teacherId],@"id", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIHome@"home/getEvaluationInfo.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            NSURL  *headerUrl = [NSURL  URLWithString:[NSString  stringWithFormat:@"%@",[[responseObject  objectForKey:@"result"] objectForKey:@"headUrl"]]];
            [self.headerImv  sd_setImageWithURL:headerUrl placeholderImage:[UIImage  imageNamed:@"Placeholder200_200"]];
            self.nameLab.text = [NSString  stringWithFormat:@"%@",[[responseObject  objectForKey:@"result"] objectForKey:@"name"]];
            
            NSArray  *label = [[responseObject  objectForKey:@"result"] objectForKey:@"label"];
            if ([label  isKindOfClass:[NSArray  class]] && label.count > 0) {
                NSInteger  count = [label  count];
                [labelDataArray  removeAllObjects];
                for (int i = 0; i < count; i ++) {
                    NSDictionary  *tempDic = [NSDictionary  dictionaryWithObjectsAndKeys:[label  objectAtIndex:i],@"name", nil];
                    [labelDataArray  addObject:tempDic];
                }
                [autoSizeLabView  reloadLabelViewWithArray:labelDataArray];
                if (!self.labelView.hidden) {
                    self.labelViewHeight.constant = autoSizeLabView.frame.size.height + 110;
                }

            }
        
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.commentTextView  resignFirstResponder];
}

#pragma mark - UITextView Delegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    self.placeholderLab.hidden = YES;
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length == 0) {
        self.placeholderLab.hidden = NO;
    }else{
        self.placeholderLab.hidden = YES;
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
    NSInteger number = [textView.text length];
    if (number > 300) {
        self.numLab.hidden = NO;
        self.numLab.text = @"0";
        textView.text = [textView.text substringToIndex:300];
        return;
    }
    if (number > 249) {
        self.numLab.hidden = NO;
        self.numLab.text = [NSString  stringWithFormat:@"%ld",MAX(0, 300-number)];
    }else {
        self.numLab.hidden = YES;
    }
}

#pragma mark - AutoSizeLabel Delegate
- (void)selectAutoSizeLabel:(NSInteger)index
{
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
